import os
import requests
import swisseph as swe
from datetime import datetime, timedelta
from flask import Flask, request, jsonify, render_template, url_for, redirect, send_from_directory
from flask_cors import CORS
from collections import OrderedDict 
from dotenv import load_dotenv

# 加载 .env 文件
load_dotenv()
api_key = os.getenv("DEEPSEEK_API_KEY")

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 日出日落相关函数
def jd_to_utc(jd):
    year, month, day, hour = swe.revjul(jd, swe.GREG_CAL)
    # 将小时的小数部分转换为分钟和秒
    minutes = (hour % 1) * 60
    seconds = (minutes % 1) * 60
    return datetime(year, month, day, int(hour), int(minutes), int(seconds))

# 转换为本地时间（假设时区为 UTC+8）
# timezone = 8
def get_planet_rise_set_transit(year, month, day, hour, minute, longitude, latitude, planet, altitude=0):
    jd = swe.julday(year, month, day-1, hour + minute / 60.0)
    flags = swe.FLG_SWIEPH
    geopos = [longitude, latitude, altitude]

    # 获取行星的升起、落下和中天时刻
    rise_info = swe.rise_trans(jd, planet, swe.CALC_RISE, geopos, flags=flags)
    set_info = swe.rise_trans(jd, planet, swe.CALC_SET, geopos, flags=flags)
    transit_info = swe.rise_trans(jd, planet, 4, geopos, flags=flags)

    rise = rise_info[1][0]
    set = set_info[1][0]
    transit = transit_info[1][0]

    rise_utc = jd_to_utc(rise)
    set_utc = jd_to_utc(set)
    transit_utc = jd_to_utc(transit)

    # 计算赤纬角
    planet_position = swe.calc_ut(jd, planet, swe.FLG_EQUATORIAL)
    declination = planet_position[0][1]  # 赤纬角（单位：度）

    # 转换为本地时间（假设时区为 UTC+8）
    timezone = 8
    rise_local = rise_utc + timedelta(hours=timezone)
    set_local = set_utc + timedelta(hours=timezone)
    transit_local = transit_utc + timedelta(hours=timezone)

    return {
        'rise': rise_local,
        'set': set_local,
        'transit': transit_local,
        'declination': declination,
    }

def get_sunrise_sunset(year, month, day, hour, minute, longitude, latitude, altitude=0):
    # 将日期和时间转换为儒略日（浮动类型）
    jd0 = swe.julday(year, month, day-1, hour + minute / 60.0)
    jd = swe.julday(year, month, day-1)
    # 设置太阳的升起和落下的标志
    flags = swe.FLG_SWIEPH

    # 创建 geopos 列表，包含经度、纬度和高度
    geopos = [longitude, latitude, altitude]

    # 获取日出时刻（浮动型的儒略日）
    sunrise_info = swe.rise_trans(jd, swe.SUN, swe.CALC_RISE, geopos, flags=flags)
    # 获取日落时刻（浮动型的儒略日）
    sunset_info = swe.rise_trans(jd, swe.SUN, swe.CALC_SET, geopos, flags=flags)
    # 获取太阳中天时刻（浮动型的儒略日）
    transit_info = swe.rise_trans(jd, swe.SUN, 4, geopos, flags=flags)

    # 获取日出、日落和太阳中天的时间（浮动型的儒略日）
    sunrise = sunrise_info[1][0]
    sunset = sunset_info[1][0]
    transit = transit_info[1][0]

    # 将时间（浮动型的儒略日）转换为 UTC 时间
    # sunrise_time = swe.revjul(sunrise, swe.GREG_CAL)
    # sunset_time = swe.revjul(sunset, swe.GREG_CAL)
    # transit_time = swe.revjul(transit, swe.GREG_CAL)
    #
    # sunrise_utc = datetime(sunrise_time[0], sunrise_time[1], sunrise_time[2],
    #                        int(sunrise_time[3]), int((sunrise_time[3] % 1) * 60),int((sunrise_time[3] % 0.1) * 60))
    # sunset_utc = datetime(sunset_time[0], sunset_time[1], sunset_time[2],
    #                       int(sunset_time[3]), int((sunset_time[3] % 1) * 60),int((sunset_time[3] % 0.1) * 60))
    # transit_utc = datetime(transit_time[0], transit_time[1], transit_time[2],
    #                        int(transit_time[3]), int((transit_time[3] % 1) * 60))

    sunrise_utc = jd_to_utc(sunrise)
    sunset_utc = jd_to_utc(sunset)
    transit_utc = jd_to_utc(transit)

    # 计算日照时长
    daylight_duration = sunset_utc - sunrise_utc

    # 获取太阳、月亮赤纬角
    sun_position = swe.calc_ut(jd0, swe.SUN, swe.FLG_EQUATORIAL)
    sun_declination = sun_position[0][1]  # 太阳赤纬角（单位：度）

    moon_position = swe.calc_ut(jd0, swe.MOON, swe.FLG_EQUATORIAL)
    moon_declination = moon_position[0][1]

    # 获取月出月落时间
    moonrise_info = swe.rise_trans(jd, swe.MOON, swe.CALC_RISE, geopos, flags=flags)
    moonset_info = swe.rise_trans(jd, swe.MOON, swe.CALC_SET, geopos, flags=flags)

    moonrise = moonrise_info[1][0]
    moonset = moonset_info[1][0]

    moonrise_time = swe.revjul(moonrise, swe.GREG_CAL)
    moonset_time = swe.revjul(moonset, swe.GREG_CAL)

    moonrise_utc = datetime(moonrise_time[0],moonrise_time[1], moonrise_time[2],
                            int(moonrise_time[3]), int((moonrise_time[3] % 1) * 60),int((moonrise_time[3] % 0.1) * 60))
    moonset_utc = datetime(moonset_time[0], moonset_time[1], moonset_time[2],
                           int(moonset_time[3]), int((moonset_time[3] % 1) * 60),int((moonset_time[3] % 0.1) * 60))

    # 转换为本地时间（假设时区为 UTC+8）
    timezone = 8
    sunrise_local = sunrise_utc + timedelta(hours=timezone)
    sunset_local = sunset_utc + timedelta(hours=timezone)
    transit_local = transit_utc + timedelta(hours=timezone)
    moonrise_local = moonrise_utc + timedelta(hours=timezone)
    moonset_local = moonset_utc + timedelta(hours=timezone)

    return {
        'sunrise': sunrise_local,
        'sunset': sunset_local,
        'transit': transit_local,
        'daylight_duration': daylight_duration,
        'sun_declination': sun_declination,
        'moonrise': moonrise_local,
        'moonset': moonset_local,
        'moon_declination': moon_declination,
    }

# 修改根路由，重定向到 newcalendar.html
@app.route("/")
def index():
    return redirect(url_for('solar'))

@app.route("/newai.html")
def newai():
    return render_template("newai.html")

@app.route("/newcalendar.html")
def newcalendar():
    return render_template("newcalendar.html")

@app.route("/十二宫图.html")
def zodiac():
    return render_template("十二宫图.html")

@app.route("/newmoon.html")
def newmoon():
    return render_template("newmoon.html")

# 添加 moon.html 路由
@app.route("/moon.html")
def moon():
    return render_template("moon.html")

@app.route("/newdata.html")
def newdata():
    return render_template("newdata.html")

@app.route("/solar_system.html")
def solar():
    return render_template("solar_system.html")

# 添加处理 topic 内容的路由
@app.route("/topic<int:topic_id>")
def topic(topic_id):
    try:
        return render_template(f"data/topic{topic_id}.html")
    except:
        return "内容不存在", 404
    
@app.route("/direction.html")
def newdirection():
    return render_template("direction.html")

# 添加 JSON 文件路由
@app.route("/tibetan_lunar_calendar_2023_2030.json")
def tibetan_calendar():
    return send_from_directory('static', 'tibetan_lunar_calendar_2023_2030.json')

@app.route("/calendar_data/calendar_<int:year>.json")
def calendar_data(year):
    return send_from_directory('static/calendar_data', f'calendar_{year}.json')

@app.route("/celestial_data/city_index.json")
def city_index():
    return send_from_directory('static/celestial_data', 'city_index.json')

@app.route("/celestial_data/<path:filename>")
def celestial_data(filename):
    return send_from_directory('static/celestial_data', filename)

@app.route("/ask", methods=["POST"])
def ask():
    data = request.get_json()
    user_question = data.get("question")

    if not user_question:
        return jsonify({"error": "No question provided"}), 400

    try:
        # DeepSeek API endpoint
        url = "https://api.deepseek.com/v1/chat/completions"
        
        headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }
        
        payload = {
            "model": "deepseek-chat",
            "messages": [{"role": "user", "content": user_question}]
        }

        response = requests.post(url, json=payload, headers=headers)
        response_data = response.json()
        
        if response.status_code == 200:
            answer = response_data["choices"][0]["message"]["content"]
            return jsonify({"answer": answer})
        else:
            return jsonify({"error": f"API Error: {response_data.get('error', 'Unknown error')}"}), 500

    except Exception as e:
        return jsonify({"error": str(e)}), 500

# 添加日出日落计算API
@app.route('/api/calculate', methods=['POST'])
def calculate_sun_moon():
    if request.method == 'POST':
        data = request.get_json()
        latitude = float(data['latitude'])
        longitude = float(data['longitude'])
        date_str = data['date']
        time_str = data.get('time', '00:00')  # 默认时间为 00:00
        year, month, day = map(int, date_str.split('-'))
        hour, minute = map(int, time_str.split(':'))

        result = get_sunrise_sunset(year, month, day, hour, minute, longitude, latitude)

        # 格式化日照时长为 h小时min分钟 格式
        daylight_duration = result['daylight_duration']
        total_seconds = daylight_duration.total_seconds()
        hours = int(total_seconds // 3600)
        minutes = int((total_seconds % 3600) // 60)
        formatted_duration = f"{hours}h{minutes}min"

        # 返回 JSON 格式数据
        return jsonify({
             'sunrise': result['sunrise'].strftime('%H:%M:%S'),
            'sunset': result['sunset'].strftime('%H:%M:%S'),
            'sun_declination': f"{result['sun_declination']:.6f}",
            'daylight_duration': formatted_duration,
            'moonrise': result['moonrise'].strftime('%H:%M:%S'),
            'moonset': result['moonset'].strftime('%H:%M:%S'),
            'moon_declination': f"{result['moon_declination']:.6f}",
        })
# 行星接口
@app.route('/api/planets', methods=['POST'])
def planets():
    if request.method == 'POST':
        data = request.get_json()
        latitude = float(data['latitude'])
        longitude = float(data['longitude'])
        date_str = data['date']
        time_str = data.get('time', '00:00')  # 默认时间为 00:00
        year, month, day = map(int, date_str.split('-'))
        hour, minute = map(int, time_str.split(':'))

        planets = OrderedDict({
            '太阳': swe.SUN,
            '月球': swe.MOON,
            '水星': swe.MERCURY,
            '金星': swe.VENUS,
            '火星': swe.MARS,
            '木星': swe.JUPITER,
            '土星': swe.SATURN
        })

        results = {}
        for planet_name, planet_code in planets.items():
            result = get_planet_rise_set_transit(year, month, day, hour, minute, longitude, latitude, planet_code)
            results[planet_name] = {
                'rise': result['rise'].strftime('%Y-%m-%d %H:%M:%S'),
                'set': result['set'].strftime('%Y-%m-%d %H:%M:%S'),
                'transit': result['transit'].strftime('%Y-%m-%d %H:%M:%S'),
                'declination': f"{result['declination']:.6f}°",
            }

        # 返回 JSON 格式数据
        return jsonify(results)
if __name__ == "__main__":
    app.run(debug=True)
